"use strict";

var Exchange = function () {};

Exchange.prototype = {
    init: function () {
       LocalContractStorage.set('withdraw', JSON.stringify([])); 
    },
    getAssets: function () {
        return LocalContractStorage.get(Blockchain.transaction.from)
    },
    getWithdraw: function () {
        return LocalContractStorage.get('withdraw');
    },
    deleteWithdraw: function (id) {
        var withdraw = JSON.parse(LocalContractStorage.get('withdraw'));
        for (var i = 0; i < withdraw.length; i++) {
            if (withdraw[i].id == id) {
                withdraw.splice(i, 1);
                LocalContractStorage.del('withdraw');
                LocalContractStorage.set('withdraw', JSON.stringify(withdraw));
            }
        }
    },
    withdraw: function (tokenName) {
        var user = JSON.parse(LocalContractStorage.get(Blockchain.transaction.from));
        var withdraw = JSON.parse(LocalContractStorage.get('withdraw'));
        var userArr = Object.prototype.toString.call(user) == '[object Array]' ? user : [];
        var type = false;
        var amount = 0;
        for (var i = 0; i < userArr.length; i++) {
            if (userArr[i].tokenName == tokenName) {
                type = true
                amount = userArr[i].tokenNum;
                userArr[i].tokenNum = 0;
                LocalContractStorage.del(Blockchain.transaction.from);
                LocalContractStorage.set(Blockchain.transaction.from, JSON.stringify(userArr));

            }
        }

        if (!type) {
            throw new Error("Sorry, your credit is running low")
        }

        withdraw.push({
            tokenName: tokenName,
            tokenNum: amount,
            id: Blockchain.transaction.from
        })

        LocalContractStorage.del('withdraw');
        LocalContractStorage.set('withdraw', JSON.stringify(withdraw));
    },
    getTokenAll: function () {
        return LocalContractStorage.get('getTokenAll')
    },
    getBuy: function () {
        return LocalContractStorage.get('buy')
    },
    getSell: function () {
        return LocalContractStorage.get('sell')
    },
    addToken: function (tokenName) {
        var tokenAllJson = JSON.parse(LocalContractStorage.get('getTokenAll'));
        var tokenAll = Object.prototype.toString.call(tokenAllJson) == '[object Array]' ? tokenAllJson : [];
        var chat = JSON.parse(LocalContractStorage.get('chat'));
        if (!chat) {
            chat = {}
        }
        
        if (tokenAll.indexOf(tokenName) !== - 1) {
            throw new Error("Already existed" + tokenName)
        }
        tokenAll.push(tokenName);
        LocalContractStorage.del('getTokenAll');
        LocalContractStorage.set('getTokenAll', JSON.stringify(tokenAll));
        
        chat[tokenName] = [[Blockchain.transaction.timestamp * 1000, 0, 0, 0, 0]];
        LocalContractStorage.del('chat');
        LocalContractStorage.set('chat', JSON.stringify(chat));
    },
    revoke: function (rate, num, tokenName, type) {
        var buys = JSON.parse(LocalContractStorage.get('buy'));
        var buyArr = Object.prototype.toString.call(buys) == '[object Array]' ? buys : [];
        var sells = JSON.parse(LocalContractStorage.get('sell'));
        var sellArr = Object.prototype.toString.call(sells) == '[object Array]' ? sells : [];
        var address = Blockchain.transaction.from;
        var user = JSON.parse(LocalContractStorage.get(address)) || [];
        if (type == 1) {
            for (var i = 0; i < buyArr.length; i++) {
                if (buyArr[i].rate == rate && buyArr[i].num == num && buyArr[i].tokenName == tokenName && buyArr[i].address == address) {
                    var amounts = new BigNumber(buyArr[i].num * 1000000000000000000);
                    var result = Blockchain.transfer(address, amounts);
                    if (!result) {
                        throw new Error("退款失败了,地址是" + to + ", NAS:" + amount);
                    }
                    buyArr.splice(i, 1);
                    LocalContractStorage.del('buy');
                    LocalContractStorage.set('buy', JSON.stringify(buyArr));
                }
            }
        } else {
           for (var i = 0; i < sellArr.length; i++) {
                if (sellArr[i].rate == rate && sellArr[i].num == num && sellArr[i].tokenName == tokenName && sellArr[i].address == address) {
                    var nums = +rate * +num;
                    sellArr.splice(i, 1);
                    LocalContractStorage.del('buy');
                    LocalContractStorage.set('buy', JSON.stringify(buyArr));
                    var isName = false
                    for (var y = 0; y < user.length; y++) {
                        if (user[y].tokenName == tokenName) {
                            user[y].tokenNum = user[y].tokenNum + nums;
                        }
                    }

                    if (!isName) {
                        user.push({
                            tokenName: tokenName,
                            tokenNum: nums
                        })
                    }

                    LocalContractStorage.del(address);
                    LocalContractStorage.set(address, JSON.stringify(user));

                }
            } 
        }
    },
    buy: function (rate, num, tokenName) {
        var buy = JSON.parse(LocalContractStorage.get('buy'));
        var buyArr = Object.prototype.toString.call(buy) == '[object Array]' ? buy : [];
        buyArr.push({
            rate: rate,
            num: num,
            tokenName: tokenName,
            address: Blockchain.transaction.from,
            type: 1
        });
        LocalContractStorage.del('buy');
        LocalContractStorage.set('buy', JSON.stringify(buyArr));
        var chat = JSON.parse(LocalContractStorage.get('chat'));
        chat[tokenName].push([Blockchain.transaction.timestamp * 1000, 1 / rate, 1 / rate, 1 / rate, 1 / rate]);
        LocalContractStorage.del('chat');
        LocalContractStorage.set('chat', JSON.stringify(chat));
    },
    sell: function (rate, num, tokenName) {
        var sells = JSON.parse(LocalContractStorage.get('sell'));
        var sellArr = Object.prototype.toString.call(sells) == '[object Array]' ? sells : [];
        sellArr.push({
            rate: rate,
            num: num,
            tokenName: tokenName,
            address: Blockchain.transaction.from,
            type: 2
        });
        LocalContractStorage.del('sell');
        LocalContractStorage.set('sell', JSON.stringify(sellArr));
        var chat = JSON.parse(LocalContractStorage.get('chat'));
        chat[tokenName].push([Blockchain.transaction.timestamp * 1000, 1 / rate, 1 / rate, 1 / rate, 1 / rate]);
        LocalContractStorage.del('chat');
        LocalContractStorage.set('chat', JSON.stringify(chat));
    },
    chat: function () {
        return LocalContractStorage.get('chat');
    },
    trade: function () {
        var buys = JSON.parse(LocalContractStorage.get('buy'));
        var buyArr = Object.prototype.toString.call(buys) == '[object Array]' ? buys : [];
        var sells = JSON.parse(LocalContractStorage.get('sell'));
        var sellArr = Object.prototype.toString.call(sells) == '[object Array]' ? sells : [];

        for (var i = 0; i < buyArr.length; i++) {
            for (var y = 0; y < sellArr.length; y++) {
                if (buyArr[i].rate === sellArr[y].rate && buyArr[i].num === sellArr[y].num && buyArr[i].tokenName === sellArr[y].tokenName) {
                    buyArr.splice(i, 1);
                    sellArr.splice(y, 1);
                    var buyInfo = JSON.parse(LocalContractStorage.get(buyArr[i].address)) || [];
                    var isbuy = false
                    for (var z = 0; z < buyInfo.length; z++) {
                        if (buyInfo[z].tokenName == buyArr[i].tokenName) {
                            isbuy = true;
                            buyInfo[z].tokenNum = +buyInfo[z].tokenNum + +buyArr[i].rate * +buyArr[i].num;
                        }
                    }

                    if (!isbuy) {
                        buyInfo.push({
                            tokenNum: +buyArr[i].rate * +buyArr[i].num,
                            tokenName: buyArr[i].tokenName
                        }) 
                    }

                    LocalContractStorage.del(buyArr[i].address);
                    LocalContractStorage.set(buyArr[i].address, JSON.stringify(buyInfo));

                    var amounts = new BigNumber(buyArr[i].num * 1000000000000000000);
                    var result = Blockchain.transfer(sellArr[y].address, amounts);
                }
            }
        }
        LocalContractStorage.del('buy');
        LocalContractStorage.set('buy', JSON.stringify(buyArr));
        LocalContractStorage.del('sell');
        LocalContractStorage.set('sell', JSON.stringify(sellArr));
    }
};


module.exports = Exchange;
